/// <filename>Questions.aspx.cs</filename>
/// <author>Jessika Sutton (jsutton@microsoft.com)</author>
/// <datecreated>11/06/2006</datecreated>
/// <summary></summary>
/// <remarks></remarks>

using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Configuration;
using System.Collections;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.ApplicationBlocks.Data;
using Microsoft.AceEngineering.SPM.SPMBusinessLayer;
using Microsoft.AceEngineering.SPM.SPMCustomDataEntity;


public partial class Admin_Risk_Questions : Page
{
    private string strUserID;
    private DateTime dtCreatedDate=System.DateTime.Now.Date;
    private string strAddQuestionID;
    private string strAddType;
    private string strConn = ConfigurationManager.ConnectionStrings["SPMSQL"].ConnectionString.ToString();
    private System.IO.MemoryStream xmlStreamCat = new System.IO.MemoryStream();
    private System.IO.MemoryStream xmlStreamQues = new System.IO.MemoryStream();
    private System.IO.MemoryStream xmlStreamAns = new System.IO.MemoryStream();
    private int intMemLoaded;
    private int intAnsValid;
    private Guid gdCatID;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["user"] == null)
            ValidateUser();
        else
        {
            UserCDE userData = (UserCDE)Session["user"];
            if (userData.Time.AddMinutes(Int32.Parse(ConfigurationManager.AppSettings["AbsoluteExpiration"].ToString())) <= DateTime.Now)
                ValidateUser();
        }

        bool isAdmin = UsersBL.GetUserAdmin(Session["loginname"].ToString());
        if (!isAdmin)
            Response.Redirect("~/Home.aspx");

        try
        {
            gdCatID = new Guid(Request.QueryString["ID"]);
            strUserID = Session["loginname"].ToString();
            Session["CatID"] = gdCatID;
            Session["CatName"] = null;

            if (Page.IsPostBack == false)
            {
                Session["QuestionID"] = "";

                BindCatRepeater();
            }
        }
        catch(Exception ex)
        {
            Response.Redirect(Request.ApplicationPath + "/Admin/Risk/Categories.aspx");
        } 
    }

    private string GiveMeAlias(string domainAndAlias)
    {
        domainAndAlias = domainAndAlias.ToLower();
        char[] strSeperator = new char[] { '\\' };
        string[] aryAuthUser = new string[2];
        aryAuthUser = domainAndAlias.Split(strSeperator);
        return aryAuthUser[1];
    }

    private void ValidateUser()
    {
        string currAlias = GiveMeAlias(HttpContext.Current.User.Identity.Name);
        UserCDE user = UsersBL.ValidateUser(currAlias);
        if (user.Active)
        {
            Session["user"] = user;
            Session["loginname"] = user.UserAlias;
        }
        else
        {
            Response.Redirect(Request.ApplicationPath + "/Errors/NoAccess.htm");
        }
    }

    protected DataSet dsLoadDataSet(string strStoredProc)
    {
        DataSet ds = new DataSet();
        Guid gdNewID = new Guid(System.Guid.NewGuid().ToString().ToUpper());
        Guid gdQuestID = new Guid(System.Guid.NewGuid().ToString().ToUpper());

            if (strStoredProc == "APM_spgetStagingAnswers")
            {
                if (intMemLoaded == 0)
                {
                    ds = SqlHelper.ExecuteDataset(strConn, CommandType.StoredProcedure, strStoredProc);
                }
                else
                {
                    xmlStreamAns.Position = 0;
                    System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(xmlStreamAns);
                    ds.ReadXml(reader);
                }
                if(ds.Tables.Count==0)
                    ds.Tables.Add(dtLoadDataTable("Answers"));


            }
            else if (strStoredProc == "APM_spgetStagingQuestions")
            {
                if (intMemLoaded == 0)
                {
                    ds = SqlHelper.ExecuteDataset(strConn, CommandType.StoredProcedure, strStoredProc);
                }
                else
                {
                    xmlStreamQues.Position = 0;
                    System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(xmlStreamQues);
                    ds.ReadXml(reader);
                }
                if (ds.Tables.Count == 0)
                {
                    ds.Tables.Add(dtLoadDataTable("Questions"));

                    DataRow drQ = ds.Tables[0].NewRow();
                    drQ["QuestionID"] = gdNewID;
                    drQ["QuestionCategoryID"] = gdCatID;
                    drQ["QuestionText"] = "";
                    drQ["SequenceOrder"] = 1;
                    ds.Tables[0].Rows.InsertAt(drQ, 0);

                }


            }
            else
            {
                ds = SqlHelper.ExecuteDataset(strConn, CommandType.StoredProcedure, strStoredProc);
            }

        return ds;
    }
    protected DataTable dtLoadDataTable(string strTableName)
    {
        DataTable dt = new DataTable(strTableName);

        if (strTableName == "Questions")
        {
            DataColumn[] colQuestions = new DataColumn[9];
            colQuestions[0] = new DataColumn("QuestionID", System.Type.GetType("System.String"));
            dt.Columns.Add(colQuestions[0]);
            colQuestions[1] = new DataColumn("QuestionName", System.Type.GetType("System.String"));
            dt.Columns.Add(colQuestions[1]);
            colQuestions[2] = new DataColumn("QuestionText", System.Type.GetType("System.String"));
            dt.Columns.Add(colQuestions[2]);
            colQuestions[3] = new DataColumn("QuestionCategoryID", System.Type.GetType("System.String"));
            dt.Columns.Add(colQuestions[3]);
            colQuestions[4] = new DataColumn("QuestionType", System.Type.GetType("System.Int32"));
            dt.Columns.Add(colQuestions[4]);
            colQuestions[5] = new DataColumn("Weight", System.Type.GetType("System.Int32"));
            dt.Columns.Add(colQuestions[5]);
            colQuestions[6] = new DataColumn("SequenceOrder", System.Type.GetType("System.Int32"));
            dt.Columns.Add(colQuestions[6]);
            colQuestions[7] = new DataColumn("CreatedDate", System.Type.GetType("System.DateTime"));
            dt.Columns.Add(colQuestions[7]);
            colQuestions[8] = new DataColumn("CreatedBy", System.Type.GetType("System.String"));
            dt.Columns.Add(colQuestions[8]);
        }

        if (strTableName == "Answers")
        {
            DataColumn[] colAns = new DataColumn[8];
            colAns[0] = new DataColumn("QuestionID", System.Type.GetType("System.String"));
            dt.Columns.Add(colAns[0]);
            colAns[1] = new DataColumn("AnswerID", System.Type.GetType("System.String"));
            dt.Columns.Add(colAns[1]);
            colAns[2] = new DataColumn("AnswerName", System.Type.GetType("System.String"));
            dt.Columns.Add(colAns[2]);
            colAns[3] = new DataColumn("AnswerText", System.Type.GetType("System.String"));
            dt.Columns.Add(colAns[3]);
            colAns[4] = new DataColumn("AnswerOrder", System.Type.GetType("System.Int32"));
            dt.Columns.Add(colAns[4]);
            colAns[5] = new DataColumn("AnswerWt", System.Type.GetType("System.Int32"));
            dt.Columns.Add(colAns[5]);
            colAns[6] = new DataColumn("CreatedBy", System.Type.GetType("System.String"));
            dt.Columns.Add(colAns[6]);
            colAns[7] = new DataColumn("CreatedDate", System.Type.GetType("System.DateTime"));
            dt.Columns.Add(colAns[7]);
        }
        return dt;
    }

    protected void BindCatRepeater()
    {
        DataSet ds = dsLoadDataSet("APM_spgetStagingCategory");
        DataView dv = ds.Tables[0].DefaultView;

        if (!string.IsNullOrEmpty(Session["CatID"].ToString()))
        {
            dv.RowFilter = "QuestionCategoryID = '" + Session["CatID"].ToString() + "'";
        }
        rptCategory.DataSource = dv;
        rptCategory.DataBind();
        ds.WriteXml(xmlStreamCat, XmlWriteMode.IgnoreSchema);

    }
    protected void rptCategory_ItemDataBound(Object sender, RepeaterItemEventArgs e)
    {
        DataView dvQuestions = dsLoadDataSet("APM_spgetStagingQuestions").Tables[0].DefaultView;
        DataView dvAnswers = dsLoadDataSet("APM_spgetStagingAnswers").Tables[0].DefaultView;

        foreach (RepeaterItem ri in rptCategory.Items)
        {

            TextBox txtCatID = (TextBox)ri.FindControl("txtCatID");
            TextBox txtCatName = (TextBox)ri.FindControl("txtCatName");

            string strCatID = txtCatID.Text.ToString();
            dvQuestions.RowFilter = "QuestionCategoryID='" + strCatID.ToUpper() + "'";
            //dvQuestions.Sort = "SequenceOrder ASC";

            Session["CatID"] = strCatID;
            Session["CatName"] = txtCatName.Text.ToString();

            int QCount = dvQuestions.Count;

            Repeater rptQuest = (Repeater)ri.FindControl("rptQuestions");
            if (QCount == 0)
            {
                DataTable dtAddNewQuestions = new DataTable();
                Guid gdNewQuestID = new Guid(System.Guid.NewGuid().ToString().ToUpper());

                dtAddNewQuestions = dtLoadDataTable("Questions");
                DataRow dr = dtAddNewQuestions.NewRow();
                dr["QuestionCategoryID"] = strCatID;
                dr["QuestionID"] = gdNewQuestID;
                dr["QuestionText"] = "";
                dr["SequenceOrder"] = 1;
                dtAddNewQuestions.Rows.InsertAt(dr, 0);

                dvQuestions = dtAddNewQuestions.DefaultView;
            }
            rptQuest.DataSource = dvQuestions;
            rptQuest.DataBind();

            foreach (RepeaterItem riQ in rptQuest.Items)
            {
                DataTable dtAddNewAns = new DataTable();
                Guid gdNewAnsID = new Guid(System.Guid.NewGuid().ToString().ToUpper());

                TextBox txtQID = (TextBox)riQ.FindControl("txtQuestID");
                dvAnswers.RowFilter = "QuestionID='" + txtQID.Text.ToUpper() + "'";

                if (dvAnswers.Count == 0)
                {
                    dtAddNewAns = dtLoadDataTable("Answers");
                    DataRow dr = dtAddNewAns.NewRow();
                    dr["QuestionID"] = txtQID.Text.ToString();
                    dr["AnswerID"] = gdNewAnsID;
                    dr["AnswerText"] = "";
                    dr["AnswerWt"] = 0;
                    dr["AnswerOrder"] = 1;
                    dtAddNewAns.Rows.InsertAt(dr, 0);

                    dvAnswers = dtAddNewAns.DefaultView;

                }
                Repeater rptAns = (Repeater)riQ.FindControl("rptAnswers");
                rptAns.DataSource = dvAnswers;
                rptAns.DataBind();
            }
        }
        Session["CatID"] = null;
        Session["CatName"] = null;

    }
    protected void rptQuestions_ItemDataBound(Object sender, RepeaterItemEventArgs e)
    {
        //if (e.Item.ItemType == ListItemType.Footer)
        //{
        //    Button btnQuestAddItem = (Button)e.Item.FindControl("btnQuestAdd");
        //    btnQuestAddItem.Text = "New Question for " + Session["CatName"].ToString();
        //}
    }
    protected void rptAnswers_ItemDataBound(Object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Footer)
        {
            Button btnAnsAddItem = (Button)e.Item.FindControl("btnAnsAdd");
            btnAnsAddItem.CommandArgument = strAddQuestionID;
            //btnAnsAddItem.Text = strAddQuestionID;
        }
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            TextBox txtQuestAddID = (TextBox)e.Item.FindControl("txtQuestAnsID");
            strAddQuestionID = txtQuestAddID.Text.ToString();
        }
    }

    private void rptCategory_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "submit")
        {
            rptCategory_Save(false, true, false);

            if (intAnsValid == 1)
            {
                string msg = "All questions must have at least one answer.";
                Page pge = (Page)this.Page;
                Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, msg, "errorkey");

            }
            else
            {
                rptCategory_Submit();
            }
        }
    }
    protected void rptQuestions_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if ((String)e.CommandName == "AddQuest")
        {
            strAddType = "AddQuest";
        }

        rptCategory_Save(false,true,false);
    }
    protected void rptAnswers_ItemCommand(object source, CommandEventArgs e)
    {
        if ((String)e.CommandName == "AddAns")
        {
            strAddType = "AddAns";
            Session["QuestionID"] = (String)e.CommandArgument;
        }

        rptCategory_Save(false,true,false);
    }

    protected void DeleteBtn_Click(object sender, CommandEventArgs e)
    {
        if ((String)e.CommandArgument == "Delete")
        {
            strAddType = "Delete";
            Session["QuestionID"] = "";
            rptCategory_Save(false, false,false);
        }

    }
    protected void CancelBtn_Click(object sender, CommandEventArgs e)
    {
        Response.Redirect("Categories.aspx");
    }

    private void rptCategory_Save(bool blRedirect, bool blValidate, bool blRenumber)
    {
        bool blPageValid = true;
        if (blValidate)
        {
            Validate();
            if (!Page.IsValid)
            {
                blPageValid = false;
                StringBuilder msg = new StringBuilder("Please correct the following:\\n");
                // Loop through all validation controls to see which
                // generated the errors.
                foreach (IValidator aValidator in this.Validators)
                {
                    if (!aValidator.IsValid)
                    {
                        msg.Append("- " + aValidator.ErrorMessage + "\\n");
                    }
                }
                Page pge = (Page)this.Page;
                Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, msg.ToString(), "errorkey");
            }
        }
        if ((!blValidate) || (blValidate && blPageValid))
        {

            #region Declaration of variables
            Int32 intSeqOrder = 0;
            Int32 intWeight = 0;
            Int32 intOrder = 0;
            int i = 0;
            int intAnsWt = 0;
            int intAnsCnt = 0;
            #endregion

            #region Create datatables
            DataTable dtAns = new DataTable("Answers");
            DataTable dtQuestions = new DataTable("Questions");

            if (dtQuestions.Columns.Count == 0)
            {
                DataColumn[] colQuestions = new DataColumn[9];
                colQuestions[0] = new DataColumn("QuestionID", System.Type.GetType("System.String"));
                dtQuestions.Columns.Add(colQuestions[0]);
                colQuestions[1] = new DataColumn("QuestionName", System.Type.GetType("System.String"));
                dtQuestions.Columns.Add(colQuestions[1]);
                colQuestions[2] = new DataColumn("QuestionText", System.Type.GetType("System.String"));
                dtQuestions.Columns.Add(colQuestions[2]);
                colQuestions[3] = new DataColumn("QuestionCategoryID", System.Type.GetType("System.String"));
                dtQuestions.Columns.Add(colQuestions[3]);
                colQuestions[4] = new DataColumn("QuestionType", System.Type.GetType("System.Int32"));
                dtQuestions.Columns.Add(colQuestions[4]);
                colQuestions[5] = new DataColumn("Weight", System.Type.GetType("System.Int32"));
                dtQuestions.Columns.Add(colQuestions[5]);
                colQuestions[6] = new DataColumn("SequenceOrder", System.Type.GetType("System.Int32"));
                dtQuestions.Columns.Add(colQuestions[6]);
                colQuestions[7] = new DataColumn("CreatedDate", System.Type.GetType("System.DateTime"));
                dtQuestions.Columns.Add(colQuestions[7]);
                colQuestions[8] = new DataColumn("CreatedBy", System.Type.GetType("System.String"));
                dtQuestions.Columns.Add(colQuestions[8]);
            }
            DataSet dsXML = new DataSet("SPMQuestions");
            dsXML.Tables.Add(dtQuestions);

            if (dtAns.Columns.Count == 0)
            {
                DataColumn[] colAns = new DataColumn[8];
                colAns[0] = new DataColumn("QuestionID", System.Type.GetType("System.String"));
                dtAns.Columns.Add(colAns[0]);
                colAns[1] = new DataColumn("AnswerID", System.Type.GetType("System.String"));
                dtAns.Columns.Add(colAns[1]);
                colAns[2] = new DataColumn("AnswerName", System.Type.GetType("System.String"));
                dtAns.Columns.Add(colAns[2]);
                colAns[3] = new DataColumn("AnswerText", System.Type.GetType("System.String"));
                dtAns.Columns.Add(colAns[3]);
                colAns[4] = new DataColumn("AnswerOrder", System.Type.GetType("System.Int32"));
                dtAns.Columns.Add(colAns[4]);
                colAns[5] = new DataColumn("AnswerWt", System.Type.GetType("System.Int32"));
                dtAns.Columns.Add(colAns[5]);
                colAns[6] = new DataColumn("CreatedBy", System.Type.GetType("System.String"));
                dtAns.Columns.Add(colAns[6]);
                colAns[7] = new DataColumn("CreatedDate", System.Type.GetType("System.DateTime"));
                dtAns.Columns.Add(colAns[7]);
            }

            DataSet dsAXML = new DataSet("SPMAnswers");
            dsAXML.Tables.Add(dtAns);
            #endregion

            #region Loop through Category repeater
            foreach (RepeaterItem ri in rptCategory.Items)
            {

                TextBox txtCatID = (TextBox)ri.FindControl("txtCatID");
                string strCatID = txtCatID.Text;

                Repeater rptQuest = (Repeater)ri.FindControl("rptQuestions");
                int cnt = 0;
                int intQuestionRenumber = 1;

                i = rptQuest.Items.Count + 1;

                DataRow[] drQuestion = new DataRow[i];

                #region Loop through Question repeater

                foreach (RepeaterItem riQ in rptQuest.Items)
                {

                    string strID = System.Guid.NewGuid().ToString().ToUpper();

                    TextBox txtSeqOrder = (TextBox)riQ.FindControl("txtSeqOrder");
                    bool blSortOrder = Int32.TryParse(txtSeqOrder.Text.ToString(), out intSeqOrder);

                    if (blRenumber)
                    {
                        intSeqOrder = intQuestionRenumber;
                    }

                    TextBox txtQuestID = (TextBox)riQ.FindControl("txtQuestID");
                    string strQuestionID = txtQuestID.Text;

                    if (strQuestionID == "")
                    {
                        strQuestionID = strID.ToString().ToUpper();
                    }

                    TextBox txtQuestTxt = (TextBox)riQ.FindControl("txtQuestionTxt");
                    string strQuestionTxt = txtQuestTxt.Text;
                    cnt = cnt + 1;
                    CheckBox chkDelete = (CheckBox)riQ.FindControl("chkDeleteQuest");

                    if (!chkDelete.Checked || blValidate)
                    {
                        if (strQuestionTxt.Length >= 1)
                        {
                            drQuestion[cnt] = dtQuestions.NewRow();
                            drQuestion[cnt]["QuestionID"] = strQuestionID;
                            drQuestion[cnt]["QuestionName"] = strQuestionTxt;
                            drQuestion[cnt]["QuestionText"] = strQuestionTxt;
                            drQuestion[cnt]["QuestionCategoryID"] = strCatID;
                            drQuestion[cnt]["QuestionType"] = intWeight;
                            drQuestion[cnt]["Weight"] = intWeight;
                            drQuestion[cnt]["SequenceOrder"] = intSeqOrder;
                            drQuestion[cnt]["CreatedDate"] = dtCreatedDate;
                            drQuestion[cnt]["CreatedBy"] = strUserID;
                            dtQuestions.Rows.Add(drQuestion[cnt]);
                            intQuestionRenumber = intQuestionRenumber + 1;

                        }

                        int j = 0;
                        int cntA = 0;

                        Repeater rptAnswers = (Repeater)riQ.FindControl("rptAnswers");

                        int intAnswerRenumber = 1;
                        j = rptAnswers.Items.Count + 1;

                        DataRow[] drAnswer = new DataRow[j];

                        #region loop through Answer repeater
                        foreach (RepeaterItem riA in rptAnswers.Items)
                        {
                            string strAID = System.Guid.NewGuid().ToString().ToUpper();

                            TextBox txtOrder = (TextBox)riA.FindControl("txtOrder");
                            bool blOrder = Int32.TryParse(txtOrder.Text.ToString(), out intOrder);

                            if (blRenumber)
                            {
                                intOrder = intAnswerRenumber;
                            }

                            TextBox txtAnsID = (TextBox)riA.FindControl("txtAnswerID");
                            string strAnswerID = txtAnsID.Text;

                            if (strAnswerID == "")
                            {
                                strAnswerID = strAID.ToString().ToUpper();
                            }
                            TextBox txtAnswerTxt = (TextBox)riA.FindControl("txtAnswerText");
                            string strAnswerTxt = txtAnswerTxt.Text;

                            TextBox txtAnswerWt = (TextBox)riA.FindControl("txtAnswerWt");
                            bool blAnswerWt = Int32.TryParse(txtAnswerWt.Text.ToString(), out intAnsWt);
                            CheckBox chkDeleteAns = (CheckBox)riA.FindControl("chkDelete");
                            if (!chkDeleteAns.Checked||blValidate)
                            {

                                if (intOrder >= 0 & strAnswerTxt.Length >= 1)
                                {
                                    drAnswer[cntA] = dtAns.NewRow();
                                    drAnswer[cntA]["QuestionID"] = strQuestionID;
                                    drAnswer[cntA]["AnswerID"] = strAnswerID;
                                    drAnswer[cntA]["AnswerName"] = strAnswerTxt;
                                    drAnswer[cntA]["AnswerText"] = strAnswerTxt;
                                    drAnswer[cntA]["AnswerOrder"] = intOrder;
                                    drAnswer[cntA]["AnswerWt"] = intAnsWt;
                                    drAnswer[cntA]["CreatedDate"] = dtCreatedDate;
                                    drAnswer[cntA]["CreatedBy"] = strUserID;
                                    dtAns.Rows.Add(drAnswer[cntA]);
                                    intAnswerRenumber = intAnswerRenumber + 1;
                                }
                            }
                            cntA = cntA + 1;

                        }
                        if (j == 1)
                        {
                            intAnsValid = 1;
                        }
                        intAnsCnt = cntA + 1;
                    }
                    if ((strAddType == "AddAns" && Session["QuestionID"].ToString() == strQuestionID) )
                    {
                        string strAID = System.Guid.NewGuid().ToString().ToUpper();

                        DataRow dr = dtAns.NewRow();
                        dr["QuestionID"] = strQuestionID;
                        dr["AnswerID"] = strAID;
                        dr["AnswerText"] = "";
                        dr["AnswerWt"] = 0;
                        dr["AnswerOrder"] = intAnsCnt;
                        dtAns.Rows.InsertAt(dr, intAnsCnt + 20);
                        strAddType = null;
                    }

                        #endregion
                }
                if (strAddType == "AddQuest")
                {
                    Guid gdNewQuestID = new Guid(System.Guid.NewGuid().ToString().ToUpper());
                    Guid gdNewAnswerID = new Guid(System.Guid.NewGuid().ToString().ToUpper());
                    DataRow drQ = dtQuestions.NewRow();
                    drQ["QuestionID"] = gdNewQuestID;
                    drQ["QuestionCategoryID"] = strCatID;
                    drQ["QuestionText"] = "";
                    drQ["SequenceOrder"] = cnt + 1;
                    dtQuestions.Rows.InsertAt(drQ, cnt + 20);
                    strAddType = null;
                    Session["QuestionID"] = gdNewQuestID;

                    DataRow dr = dtAns.NewRow();
                    dr["QuestionID"] = gdNewQuestID;
                    dr["AnswerID"] = gdNewAnswerID;
                    dr["AnswerText"] = "";
                    dr["AnswerWt"] = 0;
                    dr["AnswerOrder"] = 1;
                    dtAns.Rows.InsertAt(dr, intAnsCnt);

                }

                #endregion
            }
            #endregion

            #region Write data to xml
            //xmlStreamQues = new System.IO.MemoryStream();
            //xmlStreamAns = new System.IO.MemoryStream();

            dsXML.WriteXml(xmlStreamQues, XmlWriteMode.IgnoreSchema);
            dsAXML.WriteXml(xmlStreamAns, XmlWriteMode.IgnoreSchema);
            intMemLoaded = 1;
            dsXML.Clear();
            dsAXML.Clear();

            dsXML.Dispose();
            dsAXML.Dispose();

            #endregion

            if (!blRedirect)
            {
                BindCatRepeater();
            }
        }
    }
    private void rptCategory_Submit()
    {
        SqlConnection scConn = new SqlConnection(strConn);
        scConn.Open();

        xmlStreamAns.Position = 0;
        xmlStreamQues.Position = 0;

        StreamReader xmlAnsStream = new StreamReader(xmlStreamAns);
        StreamReader xmlQuestStream = new StreamReader(xmlStreamQues);

        string strXMLAns = xmlAnsStream.ReadToEnd().ToString();
        string strXMLQuest = xmlQuestStream.ReadToEnd().ToString();
        using (SqlConnection myconnection = new SqlConnection(strConn))
        {

            try
            {
                //Guid gdCatID = new Guid(Session["CatID"].ToString()); ;
                gdCatID = new Guid(Request.QueryString["ID"]);
                SqlCommand scUpdate = new SqlCommand("SPM_spUploadAdminQuestionnaire", scConn);
                scUpdate.CommandType = CommandType.StoredProcedure;

                scUpdate.Parameters.Add("@QuestionCategoryID", SqlDbType.UniqueIdentifier).Value = gdCatID;
                scUpdate.Parameters.Add("@XmlAnsDocument", SqlDbType.Xml).Value = strXMLAns;
                scUpdate.Parameters.Add("@XmlQuestDocument", SqlDbType.Xml).Value = strXMLQuest;

                scUpdate.ExecuteNonQuery();
                Response.Redirect(Request.ApplicationPath + "/Admin/Risk/Categories.aspx");
            }
            catch (SqlException ex)
            {
                string strErrorType = ex.Message.ToString().Substring(0, 8);

                Page pge = (Page)this.Page;
                Microsoft.ACEEngineering.Utility.CommonProcess.APMErrorHandling(ex, Request.IsLocal, pge, Session, Request);
                if (!Request.IsLocal && strErrorType != "APMError")
                {
                    Server.ClearError();
                    Server.Transfer(Request.ApplicationPath + "/Errors/GenericErrorPage.htm");
                }
            }

            finally
            {
                xmlAnsStream.Close();
                xmlQuestStream.Close();
                scConn.Close();
                //Response.Redirect(Request.ApplicationPath + "/Workflow/Default.aspx?Action=1");
            }
        }
    }

    override protected void OnInit(EventArgs e)
    {
        base.OnInit(e);
        rptCategory.ItemCommand += new RepeaterCommandEventHandler(rptCategory_ItemCommand);

    }


}
